package com.sjq.supplier.controller;


import com.sjq.supplier.entity.Goods;
import com.sjq.supplier.service.GoodsService;
import com.sjq.supplier.util.OrderGenerator;
import com.sjq.supplier.util.Result;
import lombok.extern.slf4j.Slf4j;
import com.sjq.supplier.entity.Order;
import com.sjq.supplier.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

/**
 * (Order)表控制层
 *
 * @author makejava
 * @since 2024-01-02 14:54:51
 */
@Slf4j
@RestController
@RequestMapping("order")
public class OrderController {
    /**
     * 服务对象
     */
    @Resource
    private OrderService orderService;
    @Resource
    private GoodsService goodsService;


    /**
     * 分页查询所有数据
     *
     * @param order 查询实体
     * @return 所有数据
     */
    @GetMapping("selectAll")
    public Result selectAll(Order order, Integer limit, Integer page) {
        if (limit == null || page == null) {
            return Result.failure("limit和page不能为空");
        }
        return orderService.selectAll(order,limit,page);
    }

    /**
     * 新增数据
     *
     * @param order 实体对象
     * @return 新增结果
     */
    @PostMapping("add")
    @Transactional(rollbackFor = Exception.class)
    public Result insert(Order order) {
        //判断是否为空
        if (order == null) {
            return Result.failure("订单信息不能为空");
        }

        //获取价格和数量,计算总价
        order.setSumprice(order.getPrice().multiply(BigDecimal.valueOf(order.getStock())));
        order.setIsvalid(1);

        //产生订单号
        order.setOrderid(OrderGenerator.generateOrderNumber());
        if (orderService.save(order)) {
            //扣除商品库存
            Goods byId = goodsService.getById(order.getGoodsid());
            Goods goods = new Goods();
            goods.setId(order.getGoodsid());
            goods.setStock(byId.getStock() - order.getStock());
            goodsService.updateById(goods);
            return Result.success("采购成功");
        }
        return Result.failure("采购失败");
    }


}

